package com.ruoyi.web.controller.system;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.AllCustomsCodes;
import com.ruoyi.system.service.IAllCustomsCodesService;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.domain.DataMatchingLs;
import com.ruoyi.system.domain.DataMatchingLsSec;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DataMatching;
import com.ruoyi.system.service.IDataMatchingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

/**
 * 数据匹配Controller
 * 
 * @author ruoyi
 * @date 2025-02-06
 */
@RestController
@RequestMapping("/system/matching")
public class DataMatchingController extends BaseController
{
    @Autowired
    private IDataMatchingService dataMatchingService;

    @Autowired
    IAllCustomsCodesService allCustomsCodesService;
    // 配置文件中存储文件路径
    @Value("${kuaiqiao.profile}")
    private String uploadDir;

    /**
     * 下载服务器上的文件
     * @return 下载的文件
     */
    @PostMapping("/downloadFile")
    public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
//        @RequestParam String fileName
        String fileName = "shujumingxi.xlsx";
        // 构建文件路径
        String filePath = uploadDir + "/" + fileName;

        // 读取文件
        InputStream inputStream = new FileInputStream(filePath);

        // 获取文件的 MIME 类型（这里假设文件是 XLSX 格式）
        String mimeType = Files.probeContentType(Paths.get(filePath));
        if (mimeType == null) {
            mimeType = "application/octet-stream";  // 默认二进制流类型
        }

        // 创建输入流资源
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        headers.add(HttpHeaders.CONTENT_TYPE, mimeType);
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(Files.size(Paths.get(filePath))));

        // 返回文件流响应
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

    /**
     * 下载服务器上的文件
     * @return 下载的文件
     */
    @PostMapping("/downloadFileLs")
    public ResponseEntity<InputStreamResource> downloadFileLs() throws IOException {
//        @RequestParam String fileName
        String fileName = "TASK.xlsx";
        // 构建文件路径
        String filePath = uploadDir + "/" + fileName;

        // 读取文件
        InputStream inputStream = new FileInputStream(filePath);

        // 获取文件的 MIME 类型（这里假设文件是 XLSX 格式）
        String mimeType = Files.probeContentType(Paths.get(filePath));
        if (mimeType == null) {
            mimeType = "application/octet-stream";  // 默认二进制流类型
        }

        // 创建输入流资源
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        headers.add(HttpHeaders.CONTENT_TYPE, mimeType);
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(Files.size(Paths.get(filePath))));

        // 返回文件流响应
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

    /**
     * 查询数据匹配列表
     */
    @PreAuthorize("@ss.hasPermi('source:detailData:list')")
    @GetMapping("/list")
    public TableDataInfo list(DataMatching dataMatching)
    {
        startPage();
        List<DataMatching> list = dataMatchingService.selectDataMatchingList(dataMatching);
        return getDataTable(list);
    }

    /**
     * 查询数据匹配列表
     */
    @PreAuthorize("@ss.hasPermi('matching:index:list')")
    @GetMapping("/listLs")
    public TableDataInfo listLs(DataMatching dataMatching)
    {
        startPage();
        List<DataMatchingLs> list = dataMatchingService.selectDataMatchingListLs(new DataMatching());
        return getDataTable(list);
    }

    /**
     * 导出数据匹配列表
     */
    @PreAuthorize("@ss.hasPermi('system:matching:export')")
    @Log(title = "数据匹配", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DataMatching dataMatching)
    {
        List<DataMatching> list = dataMatchingService.selectDataMatchingList(dataMatching);
        ExcelUtil<DataMatching> util = new ExcelUtil<DataMatching>(DataMatching.class);
        util.exportExcel(response, list, "数据匹配数据");
    }

    /**
     * 导出数据匹配列表
     */
    @Log(title = "数据匹配", businessType = BusinessType.EXPORT)
    @PostMapping("/exportLs")
    public void exportLs(HttpServletResponse response, DataMatching dataMatching, String type)
    {
        if ("3".equals(type)) {
            List<DataMatchingLs> list = dataMatchingService.selectDataMatchingListLs(dataMatching);
            ExcelUtil<DataMatchingLs> util = new ExcelUtil<DataMatchingLs>(DataMatchingLs.class);
            util.exportExcel(response, list, "数据匹配数据");
        }else if ("2".equals(type)) {
            List<DataMatchingLsSec> list = dataMatchingService.selectDataMatchingListLsSec(dataMatching);
            ExcelUtil<DataMatchingLsSec> util = new ExcelUtil<DataMatchingLsSec>(DataMatchingLsSec.class);
            util.exportExcel(response, list, "数据匹配数据");
        }

    }

    /**
     * 获取数据匹配详细信息
     */
    @PreAuthorize("@ss.hasPermi('source:detailData:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(dataMatchingService.selectDataMatchingById(id));
    }

    /**
     * 新增数据匹配
     */
    @PreAuthorize("@ss.hasPermi('system:matching:add')")
    @Log(title = "数据匹配", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DataMatching dataMatching)
    {
        return toAjax(dataMatchingService.insertDataMatching(dataMatching));
    }

    /**
     * 修改数据匹配
     */
    @PreAuthorize("@ss.hasPermi('source:detailData:edit')")
    @Log(title = "数据匹配", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DataMatching dataMatching)
    {
        return toAjax(dataMatchingService.updateDataMatching(dataMatching));
    }

    /**
     * 修改数据匹配
     */
    @Log(title = "数据匹配", businessType = BusinessType.UPDATE)
    @PutMapping("/updateDataMatchingLs")
    public AjaxResult editDataMatchingLs(@RequestBody DataMatchingLs dataMatching)
    {
        return toAjax(dataMatchingService.updateDataMatchingLs(dataMatching));
    }

    /**
     * 删除数据匹配
     */
    @PreAuthorize("@ss.hasPermi('source:detailData:remove')")
    @Log(title = "数据匹配", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(dataMatchingService.deleteDataMatchingByIds(ids));
    }

    /**
     * 删除数据匹配
     */
    @PreAuthorize("@ss.hasPermi('system:matching:remove')")
    @Log(title = "数据匹配", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteData")
    public AjaxResult deleteData()
    {
        return success(dataMatchingService.deleteDataMatchingData());
    }

    /**
     * 删除数据匹配
     */
    @PreAuthorize("@ss.hasPermi('system:matching:remove')")
    @Log(title = "数据匹配", businessType = BusinessType.DELETE)
	@DeleteMapping("/removeLs/{ids}")
    public AjaxResult removeLs(@PathVariable String[] ids)
    {
        return toAjax(dataMatchingService.deleteDataMatchingLsByIds(ids));
    }

    /**
     * 新增数据匹配
     */
    @Log(title = "数据匹配", businessType = BusinessType.INSERT)
    @PostMapping("/matchData")
    public AjaxResult matchData(@RequestParam("file") MultipartFile file,String type) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        dataMatchingService.importExcelData(file.getInputStream(),type);
//        ajaxResult.put(AjaxResult.DATA_TAG, dataMatchingService.importExcelData(file.getInputStream() , type));
        return ajaxResult;
    }

    /**
     * 新增数据匹配
     */
    @Log(title = "数据匹配", businessType = BusinessType.INSERT)
    @PostMapping("/dataPro")
    public AjaxResult dataPro() throws Exception {
        dataMatchingService.dataProFir();
        return AjaxResult.success();
    }

    /**
     * 新增数据匹配
     */
//    @PreAuthorize("@ss.hasPermi('system:matching:add')")
//    @Log(title = "第三步数据匹配", businessType = BusinessType.INSERT)
//    @PostMapping("/matchDataSec")
//    public AjaxResult matchDataSec() {
//        AjaxResult ajaxResult = AjaxResult.success();
//        ajaxResult.put("data", dataMatchingService.importExcelData());
//        return ajaxResult;
//    }

    /**
     * 新增数据匹配
     */
    @Log(title = "第二步数据匹配", businessType = BusinessType.INSERT)
    @PostMapping("/noticePy")
    public AjaxResult noticePy() {
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("data", dataMatchingService.noticePy());
        return ajaxResult;
    }


    /**
     * 新增数据匹配
     */
    @Log(title = "数据匹配", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public JSONObject uploadFile(@RequestParam("file") MultipartFile file, String type) {
        JSONObject res = new JSONObject();
        if (file.isEmpty()) {
            res.put("error", "文件不能为空");
            return res;
        }
        try {
            InputStream inputStream = file.getInputStream();
//
//            AsyncManager.me().execute(AsyncFactory.importExcelDataAll(inputStream,type));
            res.put("success","禁用异步");
            res.put("code","200");
            allCustomsCodesService.importExcelData(inputStream,type);
            return res;
        } catch (Exception e) {
            res.put("error", e.getMessage());
            return res;
        }
    }

    /**
     * 新增数据匹配
     */
    @PreAuthorize("@ss.hasPermi('system:matching:add')")
    @Log(title = "数据匹配", businessType = BusinessType.INSERT)
    @PostMapping("/quitUpload")
    public AjaxResult quitUpload() {
        dataMatchingService.quitUpload();
        return success();
    }

}
